package com.ali.websocket;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.time.LocalDateTime;

/**
 * 自定义服务端处理器
 */
public class MyWebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    /**
     * 通道激活
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        System.out.println("接收连接：" + ctx.channel().id().asLongText());
    }

    /**
     * 通道读取
     */
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) {
        System.out.println("接收消息：" + textWebSocketFrame.text());

        TextWebSocketFrame textWebSocketFrame1 = new TextWebSocketFrame("已收到，" + LocalDateTime.now());
        //写入返回内容
        channelHandlerContext.write(textWebSocketFrame1);
        //刷新
        channelHandlerContext.flush();
    }

    /**
     * 通道非激活
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        System.out.println("断开连接：" + ctx.channel().id().asLongText());
    }
}
